package com.rpay.web.interceptor.authentic.strategy;

import com.rpay.common.dto.user.UserTokenDTO;
import com.rpay.common.enums.PcsResultCode;
import com.rpay.common.util.LoggerUtil;
import com.rpay.common.util.StringUtil;

import javax.servlet.http.HttpServletRequest;
import com.rpay.common.exception.SecurityException;
import com.rpay.service.config.ServiceThreadLocal;
import com.rpay.service.user.IUserTokenService;
import com.rpay.service.util.SpringUtil;

/**
 * Title：
 * Description
 *
 * @author fxg06 on 2018/4/19
 * @version 1.0
 */
public class AccessTokenControl implements BaseAccessControl {
    @Override
    public boolean authorize(HttpServletRequest request) throws SecurityException {
        String accessToken = request.getHeader("accessToken");
        if (StringUtil.isBlank(accessToken)) {
            LoggerUtil.error("accessToken is blank");
            throw new SecurityException(PcsResultCode.ACCESS_TOKEN_NOT_EXISTED);
        }
        UserTokenDTO userToken = SpringUtil.getBean(IUserTokenService.class).getUserToken(accessToken);
        if (userToken==null) {
            LoggerUtil.error("accessToken mismatch");
            throw new SecurityException(PcsResultCode.ACCESS_TOKEN_NOT_EXISTED);
        }

        ServiceThreadLocal.setAccessToken(userToken.getAccessToken());
        ServiceThreadLocal.setUserId(userToken.getUserId());

        return true;
    }
}
